﻿// ===============================================================================
// XCI.Parent 西安交通信息WinForm开发框架 2019 版权所有
// ===============================================================================

using DevExpress.XtraEditors.Controls;
using System;
using XCI.Extensions;
using XCI.Sys.Model;
using XCI.Sys.Service;
using XCI.Windows;
using XCI.Windows.Extensions;
using XCI.Windows.Forms;
using XCI.Windows.Helper;

namespace XCI.Sys.Forms
{
    /// <summary>
    /// 系统角色管理
    /// </summary>
    [FormCaption("系统角色管理")]
    public partial class FrmRoleManager : FrmBase
    {
        private GridHelper<SysRole> helper;
        private readonly bool allowSelect = SysRuntime.IsAuthorize("sys.role.select");
        private readonly bool allowInsert = SysRuntime.IsAuthorize("sys.role.insert");
        private readonly bool allowUpdate = SysRuntime.IsAuthorize("sys.role.update");
        private readonly bool allowDelete = SysRuntime.IsAuthorize("sys.role.delete");
        private readonly bool allowExport = SysRuntime.IsAuthorize("sys.role.export");
        private readonly bool allowEnable = SysRuntime.IsAuthorize("sys.role.enable");
        private readonly bool allowDisable = SysRuntime.IsAuthorize("sys.role.disable");
        private readonly bool allowAuthorize = SysRuntime.IsAuthorize("sys.role.authorize");

        public FrmRoleManager()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 页面初始化
        /// </summary>
        private void InitForm()
        {
            //1.初始化表格操作类
            helper = new GridHelper<SysRole>(gridView);
            helper.ElapsedTimeItem = labExecuteTime;

            //2.加载首页数据
            LoadFirstPageData();
            ButtonStatus();
        }

        /// <summary>
        /// 加载第一页数据
        /// </summary>
        private void LoadFirstPageData() => LoadData(1);

        /// <summary>
        /// 数据加载
        /// </summary>
        /// <param name="pageIndex">页码</param>
        private void LoadData(int? pageIndex = null)
        {
            //权限控制
            if (!allowSelect) return;

            helper.SetPageIndex(pageIndex);
            //1.获取查询条件
            var key = editKey.Text.Trim();
            var deptId = departmentTreeList.EditValue.ToStringOrEmpty();
            var status = statusCombo.SelectedValue.ToBoolOrNull();
            var paged = helper.Paged;

            helper.RunCallback(e =>
            {
                e.Result = RoleService.Instance.SelectPageList(paged, key, deptId, status);
            })
            .CompletCallback(e =>
            {
                ButtonStatus();
            })
            .RunAsync();
        }

        /// <summary>
        /// 数据编辑
        /// </summary>
        /// <param name="created">是否新建</param>
        /// <param name="model">模型对象</param>
        private void Edit(bool created, SysRole model = null)
        {
            var editForm = new FrmRoleEdit();
            editForm.SetModel(created, model);
            editForm.ShowDialogOk(LoadFirstPageData);
        }

        /// <summary>
        /// 获取选中的对象
        /// </summary>
        /// <returns>返回选中的对象</returns>
        private SysRole GetSelected()
        {
            return RoleService.Instance.SelectById(helper.SelectedId);
        }

        /// <summary>
        /// 设置按钮可用状态
        /// </summary>
        private void ButtonStatus()
        {
            btnNew.Enabled = allowInsert;
            btnEdit.Enabled = helper.HasSingleSelected && allowUpdate;
            btnCopy.Enabled = helper.HasSingleSelected && allowInsert;
            btnDelete.Enabled = helper.HasSelected && allowDelete;

            btnEnable.Enabled = helper.HasSelected && allowEnable;
            btnDisable.Enabled = helper.HasSelected && allowDisable;
            btnAuthorize.Enabled = helper.HasSingleSelected && allowAuthorize;

            btnPrint.Enabled = helper.HasData;
            btnExport.Enabled = helper.HasData && allowExport;
            btnSearch.Enabled = allowSelect;
        }

        /// <summary>
        /// 页面加载事件
        /// </summary>
        private void FrmRoleManager_Load(object sender, EventArgs e)
        {
            InitForm();
        }

        /// <summary>
        /// 表格双击事件
        /// </summary>
        private void gridView_DoubleClick(object sender, EventArgs e)
        {
            helper.DblClickRow(e, () =>
            {
                var detailsForm = new FrmRoleDetails(helper);
                detailsForm.ShowDialogOk();
            });

        }

        /// <summary>
        /// 表格选中项发生变化事件
        /// </summary>
        private void gridView_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
        {
            ButtonStatus();
        }

        private void gridView_EndSorting(object sender, EventArgs e)
        {
            helper.View.BeginDataUpdate();
            LoadData();
            helper.View.EndDataUpdate();
        }

        /// <summary>
        /// 页码变化事件
        /// </summary>
        private void gridPager_PageChanged(object sender, PagerEventArgs e)
        {
            LoadData();
        }

        /// <summary>
        /// 关键字文本框键盘事件
        /// </summary>
        private void editName_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            //回车事件回调
            EnterPressHandle(e, LoadFirstPageData);
        }

        /// <summary>
        /// 搜索按钮点击事件
        /// </summary>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            //加载首页数据
            LoadFirstPageData();
        }

        /// <summary>
        /// 状态发生变化事件
        /// </summary>
        private void statusCombo_SelectedIndexChanged(object sender, EventArgs e)
        {
            EndInit(LoadFirstPageData);
        }

        /// <summary>
        /// 新建事件
        /// </summary>
        private void btnNew_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Edit(true, RoleService.Instance.New());
        }

        /// <summary>
        /// 修改事件
        /// </summary>
        private void btnEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Edit(false, GetSelected());
        }

        /// <summary>
        /// 复制事件
        /// </summary>
        private void btnCopy_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Edit(true, RoleService.Instance.Copy(GetSelected()));
        }

        /// <summary>
        /// 删除事件
        /// </summary>
        private void btnDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            helper.Delete(() => { RoleService.Instance.Delete(helper.SelectedIds).IfTrue(() => { LoadData(); }); });
        }

        /// <summary>
        /// 导出事件
        /// </summary>
        private void btnExport_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var key = editKey.Text.Trim();
            var deptId = departmentTreeList.EditValue.ToStringOrEmpty();
            var status = statusCombo.SelectedValue.ToBoolOrNull();
            ExcelExportCore(() => RoleService.Instance.Export(key, deptId, status), "系统角色");
        }

        /// <summary>
        /// 打印事件
        /// </summary>
        private void btnPrint_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var key = editKey.Text.Trim();
            var deptId = departmentTreeList.EditValue.ToStringOrEmpty();
            var status = statusCombo.SelectedValue.ToBoolOrNull();
            var list = RoleService.Instance.SelectList(key, deptId, status);
            ReportObject.From("r.sys.role").SetObjectDataSource(list).Preview();
        }

        private void BtnAuthorize_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var title = $"{helper.Selected.Name} - 功能模块授权";
            var frm = new FrmModuleAuthorize(helper.SelectedId, title);
            frm.ShowDialogOk();
        }

        private void btnEnable_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            helper.StatusConfirm("启用",
                () => { RoleService.Instance.UpdateStatus(helper.SelectedIds, true).IfTrue(() => { LoadData(); }); });
        }

        private void btnDisable_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            helper.StatusConfirm("禁用",
                () => { RoleService.Instance.UpdateStatus(helper.SelectedIds, false).IfTrue(() => { LoadData(); }); });
        }

        private void departmentTreeList_EditValueChanged(object sender, EventArgs e)
        {
            departmentTreeList.Properties.Buttons[1].Visible = departmentTreeList.EditValue != null;
            LoadFirstPageData();
        }

        private void departmentTreeList_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (e.Button.Index == 1)
            {
                departmentTreeList.EditValue = null;
            }
        }
    }
}